package com.iaz.tech.tools.uml.file.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.iaz.tech.tools.uml.IUMLNeuronAble;
import com.iaz.tech.tools.uml.file.IJSONUmlAble;
import com.iaz.tech.tools.uml.relationship.Relationship;

public abstract class NeuronRelationLoader implements IJSONUmlAble {
    /**
     * 日志
     */
	private final static Logger logger = (Logger) LoggerFactory.getLogger(NeuronRelationLoader.class);
    /**
     * 将 UML 元素转换为关联关系
     * @param umlObj
     * @return
     */
    public abstract Relationship toRelationship(IUMLNeuronAble umlObj) throws Exception;

    /**
     * 解析关联关系的 JSON 数据
     */
    @Override
    public void parseJSON(IUMLNeuronAble umlObj, JSONObject json) {
        try {
            if (umlObj == null) {
                throw new IllegalArgumentException("umlObj 不能为空");
            }
            if (json == null) {
                throw new IllegalArgumentException("json 不能为空");
            }
            // if (!(umlObj instanceof NeuronExtendRelationship)){
            //     throw new IllegalArgumentException("umlObj 必须是 NeuronExtendRelationship 类型");
            // } 
            // NeuronExtendRelationship extendsRel = (NeuronExtendRelationship) umlObj;
            Relationship relationship = this.toRelationship(umlObj);
            if (json.containsKey("dialing")) {
                relationship.setDialingStr(json.getString("dialing"));
            }
            if (json.containsKey("called")) {
                relationship.setCalledStr(json.getString("called"));
            }            
        } catch (Exception e) {
            logger.error("解析关联关系失败", e);
        }        
    }

    /**
     * 将关联关系转换为 JSON 字符串
     */ 
    @Override
    public JSONObject toJSON(IUMLNeuronAble objStruct) {
        JSONObject result = new JSONObject();
        try {
            if (objStruct == null) {
                throw new IllegalArgumentException("objStruct 不能为空");
            }
            // if (!(objStruct instanceof NeuronExtendRelationship)){
            //     throw new IllegalArgumentException("objStruct 必须是 NeuronExtendRelationship 类型");
            // } 
            // NeuronExtendRelationship extendsRel = (NeuronExtendRelationship) objStruct;
            Relationship relationship = this.toRelationship(objStruct); 
            result.put("dialing", relationship.getDialingStr());
            result.put("called", relationship.getCalledStr());  
        }catch(Exception e) {
            logger.error("转换关联关系失败", e);
            result = new JSONObject();
        }
        return result;
    }
}
